#include "UsrAI.h"
#include "AI.h"
#include "config.h"
#include <set>
#include <iostream>
#include <unordered_map>
#include <map>
#include <vector>
#include <string>
#include <cmath>
using namespace std;

// 前置声明
int getWorkerCount(int resourceType);
int getTargetCount(int resourceType);

tagGame tagUsrGame;
ins UsrIns;
int begin_x = 0, begin_y = 0;
int center_x = 0, center_y = 0;
bool home_flag = false;
int home_count = 0;
bool dock_built = false;
int dock_sn = -1;
int fishing_boat_count = 0;
char game_map[128][128] = {0};
tagInfo info;

// 游戏阶段控制
static int stage = 1;
// Stage1人口控制配置
struct Stage1PopulationControl {
    int max_population_stage1 = 24;  // Stage1最大人口限制
    int food_reserve_threshold = 400;  // 开始积累食物的阈值
    bool saving_for_upgrade = false;   // 是否正在为升级积累食物
} stage1PopControl;
// Stage2：海洋探索相关
struct ExplorationData {
    set<pair<int, int>> explored_positions;  // 已探索的海洋位置
    vector<pair<int, int>> enemy_land_positions;  // 发现的敌方大陆位置
    bool enemy_mainland_found = false;
    int exploration_radius = 1;  // 当前探索半径
} exploration;

// Stage2新增：战船管理
struct NavalForce {
    int target_warships = 6;  // 目标战船数量
    int current_warships = 0;
    vector<int> warship_sns;  // 战船SN列表
    bool naval_supremacy = false;  // 是否掌控制海权
} naval;

// 资源采集目标配置（根据阶段调整）
struct ResourceTargets {
    int target_woodcutters = 8;
    int target_hunters = 4;
    int target_miners = 3;
    int target_fishers = 5;

    int current_woodcutters = 0;
    int current_hunters = 0;
    int current_miners = 0;
    int current_fishers = 0;

    // Stage2调整资源分配
    void adjustForStage2() {
        target_woodcutters = 12;  // 增加木材需求（造船）
        target_hunters = 2;       // 减少打猎
        target_miners = 2;        // 减少采石
        target_fishers = 6;       // 增加捕鱼
    }

    int getMostNeededJob() {
        double wood_ratio = (double)current_woodcutters / target_woodcutters;
        double hunt_ratio = (double)current_hunters / target_hunters;
        double mine_ratio = (double)current_miners / target_miners;

        if (wood_ratio <= hunt_ratio && wood_ratio <= mine_ratio) {
            return RESOURCE_TREE;
        } else if (hunt_ratio <= mine_ratio) {
            return RESOURCE_GAZELLE;
        } else {
            return RESOURCE_STONE;
        }
    }

    bool needMoreWorkers(int resourceType) {
        switch(resourceType) {
            case RESOURCE_TREE: return current_woodcutters < target_woodcutters;
            case RESOURCE_GAZELLE: return current_hunters < target_hunters;
            case RESOURCE_STONE: return current_miners < target_miners;
            default: return false;
        }
    }
} resourceTargets;

// 资源分配状态跟踪
unordered_map<int, bool> resourceLocks;
unordered_map<int, int> workerAssignments;

// 原有的辅助函数保持不变
int getWorkerCount(int resourceType) {
    switch(resourceType) {
        case RESOURCE_TREE: return resourceTargets.current_woodcutters;
        case RESOURCE_GAZELLE: return resourceTargets.current_hunters;
        case RESOURCE_STONE: return resourceTargets.current_miners;
        default: return 0;
    }
}

int getTargetCount(int resourceType) {
    switch(resourceType) {
        case RESOURCE_TREE: return resourceTargets.target_woodcutters;
        case RESOURCE_GAZELLE: return resourceTargets.target_hunters;
        case RESOURCE_STONE: return resourceTargets.target_miners;
        default: return 0;
    }
}

int getDistance(int x1, int y1, int x2, int y2) {
    return abs(x1 - x2) + abs(y1 - y2);
}

double getExactDistanceSquared(double x1, double y1, double x2, double y2) {
    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}

// Stage2新增：检查升级条件
bool checkUpgradeConditions() {
    int required_buildings = 0;
    bool has_dock = false, has_storage = false, has_barracks = false, has_granary = false;

    for (const tagBuilding& b : info.buildings) {
        switch(b.Type) {
            case BUILDING_DOCK:
                if (b.Percent == 100) { has_dock = true; required_buildings++; }
                break;
            case BUILDING_STOCK:
                if (b.Percent == 100) { has_storage = true; required_buildings++; }
                break;
            case BUILDING_ARMYCAMP:
                if (b.Percent == 100) { has_barracks = true; required_buildings++; }
                break;
            case BUILDING_GRANARY:
                if (b.Percent == 100) { has_granary = true; required_buildings++; }
                break;
        }
    }

    return (required_buildings >= 2 && info.Meat >= 500);
}
// 检查是否应该停止生产村民以积累食物
bool shouldStopVillagerProduction() {
    return (info.Meat >= stage1PopControl.food_reserve_threshold) ||
           (info.Meat >= 300 && checkUpgradeConditions());
}
// Stage2新增：升级到工具时代
bool  UsrAI::upgradeToToolAge() {
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_CENTER && b.Project == 0) {
            BuildingAction(b.SN, BUILDING_CENTER_UPGRADE);
            DebugText("开始升级到工具时代！");
            return true;
        }
    }
    return false;
}

// Stage2新增：科技研究优先级
void  UsrAI::researchTechnology() {
    // 1. 市场木材升级（增加射程）
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_MARKET && b.Project == 0 &&
            info.Meat >= BUILDING_MARKET_WOOD_UPGRADE_FOOD &&
            info.Wood >= BUILDING_MARKET_WOOD_UPGRADE_WOOD) {
            BuildingAction(b.SN, BUILDING_MARKET_WOOD_UPGRADE);
            DebugText("研究木材升级技术");
            return;
        }
    }

    // 2. 仓库攻防升级
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_STOCK && b.Project == 0) {
            if (info.Meat >= BUILDING_STOCK_UPGRADE_USETOOL_FOOD) {
                BuildingAction(b.SN, BUILDING_STOCK_UPGRADE_USETOOL);
                DebugText("研究工具使用技术");
                return;
            }
        }
    }
}

// Stage2新增：海洋探索算法
void  UsrAI::exploreOcean() {
    for (const tagArmy& ship : info.armies) {
        if (ship.Sort == AT_SHIP && ship.NowState == HUMAN_STATE_IDLE) {
            // 如果还未找到敌方大陆，进行系统性探索
            if (!exploration.enemy_mainland_found) {
                // 估算己方大陆位置，向对角探索
                int target_x = 128 - center_x;
                int target_y = 128 - center_y;

                // 调整目标位置确保在海洋中
                if (target_x < 10) target_x = 10;
                if (target_x > 118) target_x = 118;
                if (target_y < 10) target_y = 10;
                if (target_y > 118) target_y = 118;

                HumanMove(ship.SN, target_x * BLOCKSIDELENGTH, target_y * BLOCKSIDELENGTH);
                DebugText("战船" + to_string(ship.SN) + "向敌方大陆方向探索");
            } else {
                // 已找到敌方大陆，巡逻海域
                if (!exploration.enemy_land_positions.empty()) {
                    auto& pos = exploration.enemy_land_positions[0];
                    // 在敌方大陆附近巡逻
                    int patrol_x = pos.first + (rand() % 21 - 10);  // ±10范围巡逻
                    int patrol_y = pos.second + (rand() % 21 - 10);
                    patrol_x = max(5, min(123, patrol_x));
                    patrol_y = max(5, min(123, patrol_y));

                    HumanMove(ship.SN, patrol_x * BLOCKSIDELENGTH, patrol_y * BLOCKSIDELENGTH);
                    DebugText("战船" + to_string(ship.SN) + "在敌方海域巡逻");
                }
            }
            break;  // 一次只控制一艘船
        }
    }
}

// Stage2新增：检测敌方大陆
void  UsrAI::detectEnemyLand() {
    for (int i = 0; i < 128; i++) {
        for (int j = 0; j < 128; j++) {
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                // 检查是否远离己方市镇中心（可能是敌方大陆）
                int dist = getDistance(i, j, center_x, center_y);
                if (dist > 30) {  // 距离阈值
                    exploration.enemy_land_positions.push_back({i, j});
                    if (!exploration.enemy_mainland_found) {
                        exploration.enemy_mainland_found = true;
                        DebugText("发现敌方大陆位置：(" + to_string(i) + "," + to_string(j) + ")");
                    }
                }
            }
        }
    }
}

// Stage2新增：海战逻辑
void  UsrAI::conductNavalWarfare() {
    // 检测敌方海军
    for (const tagArmy& enemy : info.enemy_armies) {
        if (enemy.Sort == AT_SHIP) {  // 敌方战船
            // 派遣最近的己方战船攻击
            int nearest_ship = -1;
            double min_dist = 1e9;

            for (const tagArmy& ship : info.armies) {
                if (ship.Sort == AT_SHIP && ship.NowState == HUMAN_STATE_IDLE) {
                    double dist = getExactDistanceSquared(ship.DR, ship.UR, enemy.DR, enemy.UR);
                    if (dist < min_dist) {
                        min_dist = dist;
                        nearest_ship = ship.SN;
                    }
                }
            }

            if (nearest_ship != -1) {
                HumanAction(nearest_ship, enemy.SN);
                DebugText("战船" + to_string(nearest_ship) + "攻击敌方战船" + to_string(enemy.SN));
            }
            break;  // 一次处理一个敌人
        }
    }
}

// 原有函数保持不变
void UsrAI::updateMap() {
    memset(game_map, 0, 128 * 128 * sizeof(char));

    for (int i = 0; i < 128; i++) {
        for (int j = 0; j < 128; j++) {
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                game_map[i][j] = 1;
            } else if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN) {
                game_map[i][j] = 2;
            }
        }
    }

    for (const tagBuilding& b : info.buildings) {
        int size = (b.Type == BUILDING_CENTER) ? 3 :
                  (b.Type == BUILDING_HOME || b.Type == BUILDING_DOCK) ? 2 : 3;
        for (int i = b.BlockDR; i < b.BlockDR + size && i < 128; i++) {
            for (int j = b.BlockUR; j < b.BlockUR + size && j < 128; j++) {
                game_map[i][j] = 3;
            }
        }
        if (b.Type == BUILDING_DOCK) {
            dock_built = true;
            dock_sn = b.SN;
        }
    }

    for (const tagBuilding& b : info.enemy_buildings) {
        int size = (b.Type == BUILDING_CENTER) ? 3 :
                  (b.Type == BUILDING_HOME) ? 2 : 3;
        for (int i = b.BlockDR; i < b.BlockDR + size && i < 128; i++) {
            for (int j = b.BlockUR; j < b.BlockUR + size && j < 128; j++) {
                game_map[i][j] = 4;
            }
        }
    }

    for (const tagResource& res : info.resources) {
        if (res.BlockDR >= 0 && res.BlockDR < 128 && res.BlockUR >= 0 && res.BlockUR < 128) {
            game_map[res.BlockDR][res.BlockUR] = 5;
        }
    }
}

// 原有函数保持不变
bool isAreaFree(int x, int y, int size = 2) {
    for (int i = x; i < x + size && i < 128; i++) {
        for (int j = y; j < y + size && j < 128; j++) {
            if (game_map[i][j] >= 3 && game_map[i][j] <= 5) {
                return false;
            }
        }
    }
    return true;
}

bool findDockPosition(int& dock_x, int& dock_y) {
    int bestX = -1, bestY = -1;
    int minDist = 9999;

    for (int radius = 1; radius <= 30; radius++) {
        for (int i = max(0, center_x - radius); i <= min(127, center_x + radius); i++) {
            for (int j = max(0, center_y - radius); j <= min(127, center_y + radius); j++) {
                if (i + 1 >= 128 || j + 1 >= 128) continue;
                if (game_map[i][j] != 2 || game_map[i+1][j] != 2 ||
                    game_map[i][j+1] != 2 || game_map[i+1][j+1] != 2) continue;

                bool hasLand = false;
                for (int di = -1; di <= 2; di++) {
                    for (int dj = -1; dj <= 2; dj++) {
                        int ni = i + di, nj = j + dj;
                        if (ni >= 0 && ni < 128 && nj >= 0 && nj < 128) {
                            if (game_map[ni][nj] == 1) {
                                hasLand = true;
                                break;
                            }
                        }
                    }
                    if (hasLand) break;
                }

                if (hasLand && isAreaFree(i, j, 2)) {
                    int dist = getDistance(i, j, center_x, center_y);
                    if (dist < minDist) {
                        minDist = dist;
                        bestX = i;
                        bestY = j;
                    }
                }
            }
        }
        if (bestX != -1) break;
    }

    if (bestX != -1) {
        dock_x = bestX;
        dock_y = bestY;
        return true;
    }
    return false;
}

bool findStoragePosition(int& storage_x, int& storage_y) {
    int gazelleX = -1, gazelleY = -1;
    for (const tagResource& res : info.resources) {
        if (res.Type == RESOURCE_GAZELLE) {
            gazelleX = res.BlockDR;
            gazelleY = res.BlockUR;
            break;
        }
    }

    if (gazelleX == -1) return false;

    for (int radius = 2; radius <= 6; radius++) {
        for (int i = gazelleX - radius; i <= gazelleX + radius; i++) {
            for (int j = gazelleY - radius; j <= gazelleY + radius; j++) {
                if (i >= 0 && i + 2 < 128 && j >= 0 && j + 2 < 128) {
                    bool canBuild = true;
                    for (int di = 0; di < 3; di++) {
                        for (int dj = 0; dj < 3; dj++) {
                            if (game_map[i+di][j+dj] != 1) {
                                canBuild = false;
                                break;
                            }
                        }
                        if (!canBuild) break;
                    }

                    if (canBuild && isAreaFree(i, j, 3)) {
                        storage_x = i;
                        storage_y = j;
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

int find_block(int& x, int& y, bool is_dock = false) {
    for (int i = begin_x; i < 128; i++) {
        int start_j = (i == begin_x) ? begin_y : 0;
        for (int j = start_j; j < 128; j++) {
            if (i + 1 >= 128 || j + 1 >= 128) continue;

            if (is_dock) {
                if (game_map[i][j] != 2 || game_map[i+1][j] != 2 ||
                    game_map[i][j+1] != 2 || game_map[i+1][j+1] != 2) continue;
                bool has_land = false;
                for (int di = -1; di <= 2; di++) {
                    for (int dj = -1; dj <= 2; dj++) {
                        if ((di == -1 || di == 2 || dj == -1 || dj == 2) &&
                            i+di >= 0 && i+di < 128 && j+dj >= 0 && j+dj < 128) {
                            if (game_map[i+di][j+dj] == 1) {
                                has_land = true;
                                break;
                            }
                        }
                    }
                    if (has_land) break;
                }
                if (!has_land) continue;
            } else {
                if (game_map[i][j] != 1 || game_map[i+1][j] != 1 ||
                    game_map[i][j+1] != 1 || game_map[i+1][j+1] != 1) continue;
                int height = (*info.theMap)[i][j].height;
                if ((*info.theMap)[i+1][j].height != height ||
                    (*info.theMap)[i][j+1].height != height ||
                    (*info.theMap)[i+1][j+1].height != height) continue;
            }

            if (isAreaFree(i, j, 2)) {
                x = i;
                y = j;
                begin_x = i;
                begin_y = (j + 1) % 128;
                if (begin_y == 0) begin_x++;
                return 1;
            }
        }
    }
    begin_x = 0;
    begin_y = 0;
    return 0;
}

bool isResourceValid(int resSN) {
    for (const tagResource& res : info.resources) {
        if (res.SN == resSN && res.Cnt > 0) {
            return true;
        }
    }
    return false;
}

bool lockResource(int resSN) {
    if (resourceLocks.find(resSN) == resourceLocks.end()) {
        resourceLocks[resSN] = false;
    }
    if (!resourceLocks[resSN] && isResourceValid(resSN)) {
        resourceLocks[resSN] = true;
        return true;
    }
    return false;
}

void unlockResource(int resSN) {
    if (resourceLocks.find(resSN) != resourceLocks.end()) {
        resourceLocks[resSN] = false;
    }
}

int findNearestFish(int x, int y) {
    int nearest_sn = -1;
    double min_dist = 1e9;

    for (const tagResource& res : info.resources) {
        if (res.Type == RESOURCE_FISH && res.Cnt > 0) {
            double dist = getExactDistanceSquared(x, y, res.DR, res.UR);
            if (dist < min_dist) {
                min_dist = dist;
                nearest_sn = res.SN;
            }
        }
    }
    return nearest_sn;
}

int findNearestResource(int x, int y, int resourceType) {
    int nearest_sn = -1;
    double min_dist = 1e9;

    for (const tagResource& res : info.resources) {
        if (res.Type == resourceType && res.Cnt > 0 && lockResource(res.SN)) {
            double dist = getExactDistanceSquared(x, y, res.DR, res.UR);
            if (dist < min_dist) {
                if (nearest_sn != -1) unlockResource(nearest_sn);
                min_dist = dist;
                nearest_sn = res.SN;
            } else {
                unlockResource(res.SN);
            }
        }
    }
    return nearest_sn;
}

void updateWorkForceCount() {
    resourceTargets.current_woodcutters = 0;
    resourceTargets.current_hunters = 0;
    resourceTargets.current_miners = 0;
    resourceTargets.current_fishers = 0;

    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_WORKING) {
            for (const tagResource& res : info.resources) {
                if (res.SN == farmer.WorkObjectSN) {
                    switch (res.Type) {
                        case RESOURCE_TREE:
                            resourceTargets.current_woodcutters++;
                            break;
                        case RESOURCE_GAZELLE:
                        case RESOURCE_ELEPHANT:
                            resourceTargets.current_hunters++;
                            break;
                        case RESOURCE_STONE:
                            resourceTargets.current_miners++;
                            break;
                    }
                    break;
                }
            }
        } else if (farmer.FarmerSort == 2) {
            resourceTargets.current_fishers++;
        }
    }

    // Stage2新增：统计战船数量
    naval.current_warships = 0;
    naval.warship_sns.clear();
    for (const tagArmy& army : info.armies) {
        if (army.Sort == AT_SHIP) {
            naval.current_warships++;
            naval.warship_sns.push_back(army.SN);
        }
    }
}

void UsrAI::assignFishingJobs() {
    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 2 && farmer.NowState == HUMAN_STATE_IDLE) {
            int fish_sn = findNearestFish(farmer.BlockDR, farmer.BlockUR);
            if (fish_sn != -1) {
                HumanAction(farmer.SN, fish_sn);
                DebugText("分配渔船" + to_string(farmer.SN) + "前往渔场" + to_string(fish_sn));
            } else {
                DebugText("渔船" + to_string(farmer.SN) + "开始探索新渔场");
                HumanMove(farmer.SN, farmer.DR + 35.7, farmer.UR + 35.7);
            }
        }
    }
}

void UsrAI::assignOptimalTask(tagFarmer& farmer) {
    // Stage2优先级调整：如果在Stage2，优先保证木材供应
    if (stage == 2) {
        // 优先建造市场（如果还没有）
        bool hasMarket = false;
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_MARKET) {
                hasMarket = true;
                break;
            }
        }

        if (!hasMarket && info.Wood >= BUILD_MARKET_WOOD) {
            int market_x, market_y;
            if (find_block(market_x, market_y)) {
                HumanBuild(farmer.SN, BUILDING_MARKET, market_x, market_y);
                DebugText("村民" + to_string(farmer.SN) + "建造市场");
                return;
            }
        }
    }

    // 原有的建造逻辑保持不变
    if (!dock_built && info.Wood >= BUILD_DOCK_WOOD) {
        int dock_x, dock_y;
        if (findDockPosition(dock_x, dock_y)) {
            HumanBuild(farmer.SN, BUILDING_DOCK, dock_x, dock_y);
            DebugText("村民" + to_string(farmer.SN) + "建造船坞");
            return;
        }
    }

    int currentPop = info.farmers.size() + info.armies.size();
    int popSpace = info.Human_MaxNum - currentPop;
    if (popSpace < 5 && info.Wood >= BUILD_HOUSE_WOOD) {
        int home_x, home_y;
        if (find_block(home_x, home_y) && isAreaFree(home_x, home_y)) {
            HumanBuild(farmer.SN, BUILDING_HOME, home_x, home_y);
            DebugText("村民" + to_string(farmer.SN) + "建造房屋（缓解人口瓶颈）");
            return;
        }
    }

    bool hasGazelleStore = false;
    for (const tagBuilding& b : info.buildings) {
        if (b.Type == BUILDING_STOCK) {
            hasGazelleStore = true;
            break;
        }
    }

    if (!hasGazelleStore && info.Wood >= BUILD_STOCK_WOOD) {
        int storage_x, storage_y;
        if (findStoragePosition(storage_x, storage_y)) {
            HumanBuild(farmer.SN, BUILDING_STOCK, storage_x, storage_y);
            DebugText("村民" + to_string(farmer.SN) + "建造羚羊仓库");
            return;
        }
    }

    // 按照资源缺口优先级分配工作
    int neededJobType = resourceTargets.getMostNeededJob();

    if (resourceTargets.needMoreWorkers(neededJobType)) {
        int resourceSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, neededJobType);
        if (resourceSN != -1) {
            HumanAction(farmer.SN, resourceSN);
            string jobName = (neededJobType == RESOURCE_TREE) ? "砍树" :
                           (neededJobType == RESOURCE_GAZELLE) ? "打猎" : "采石";
            DebugText("优先分配村民" + to_string(farmer.SN) + jobName);
            return;
        }
    }

    vector<int> jobPriority = {RESOURCE_TREE, RESOURCE_GAZELLE, RESOURCE_STONE};

    for (int jobType : jobPriority) {
        if (resourceTargets.needMoreWorkers(jobType)) {
            int resourceSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, jobType);
            if (resourceSN != -1) {
                HumanAction(farmer.SN, resourceSN);
                string jobName = (jobType == RESOURCE_TREE) ? "砍树" :
                               (jobType == RESOURCE_GAZELLE) ? "打猎" : "采石";
                DebugText("补充分配村民" + to_string(farmer.SN) + jobName);
                return;
            }
        }
    }

    int treeSN = findNearestResource(farmer.BlockDR, farmer.BlockUR, RESOURCE_TREE);
    if (treeSN != -1) {
        HumanAction(farmer.SN, treeSN);
        DebugText("额外分配村民" + to_string(farmer.SN) + "砍树");
        return;
    }

    HumanMove(farmer.SN, farmer.DR + 35.7, farmer.UR + 35.7);
    DebugText("村民" + to_string(farmer.SN) + "探索");
}

// 主处理逻辑（增强Stage1->Stage2升级和Stage2功能）
void UsrAI::processData() {
    info = getInfo();
    updateMap();
    updateWorkForceCount();
    resourceLocks.clear();

    // 检测游戏阶段变化
    if (stage == 1 && info.civilizationStage == CIVILIZATION_TOOLAGE) {
        stage = 2;
        resourceTargets.adjustForStage2();  // 调整资源分配目标
        DebugText("======= 进入Stage2：工具时代 =======");
    }

    if (center_x == 0 && center_y == 0) {
        for (const tagBuilding& b : info.buildings) {
            if (b.Type == BUILDING_CENTER) {
                center_x = b.BlockDR;
                center_y = b.BlockUR;
                begin_x = max(0, center_x - 5);
                begin_y = max(0, center_y - 5);
                break;
            }
        }
    }

    home_count = 0;
    fishing_boat_count = 0;
    for (const tagBuilding& building : info.buildings) {
        if (building.Type == BUILDING_HOME) {
            home_count++;
        }
    }

    for (const tagFarmer& farmer : info.farmers) {
        if (farmer.FarmerSort == 2) {
            fishing_boat_count++;
        }
    }

    home_flag = (home_count > 0);

    // 村民生产逻辑（Stage1优化）
    int currentPop = info.farmers.size() + info.armies.size();
    bool shouldProduceVillager = false;

    if (stage == 1) {
        // Stage1：限制人口并为升级积累食物
        stage1PopControl.saving_for_upgrade = shouldStopVillagerProduction();

        if (!stage1PopControl.saving_for_upgrade &&
            currentPop < stage1PopControl.max_population_stage1 &&
            info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
            shouldProduceVillager = true;
        }

        if (stage1PopControl.saving_for_upgrade) {
            DebugText("Stage1：停止生产村民，积累食物准备升级（食物:" + to_string(info.Meat) + "/500）");
        }
    } else {
        // Stage2：正常人口控制
        int targetPop = info.Human_MaxNum - 10;  // 预留军事单位空间
        if (currentPop < targetPop && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
            shouldProduceVillager = true;
        }
    }

    if (shouldProduceVillager) {
        for (const auto& b : info.buildings) {
            if (b.Type == BUILDING_CENTER && b.Project == 0) {
                BuildingAction(b.SN, BUILDING_CENTER_CREATEFARMER);
                string popInfo = (stage == 1) ?
                    to_string(currentPop) + "/" + to_string(stage1PopControl.max_population_stage1) :
                    to_string(currentPop) + "/" + to_string(info.Human_MaxNum);
                DebugText("生产村民（当前" + popInfo + "）");
                break;
            }
        }
    }
    // 通用逻辑：渔船生产和管理
    if (dock_built && fishing_boat_count < resourceTargets.target_fishers && info.Wood >= 60) {
        for (const auto& b : info.buildings) {
            if (b.Type == BUILDING_DOCK && b.Project == 0 && (stage == 1 || naval.current_warships >= naval.target_warships)) {
                BuildingAction(b.SN, BUILDING_DOCK_CREATE_SAILING);
                DebugText("船坞造渔船（" + to_string(fishing_boat_count) + "/" +
                         to_string(resourceTargets.target_fishers) + "）");
                break;
            }
        }
    }

    assignFishingJobs();

    // 通用逻辑：陆地村民任务分配
    for (auto& farmer : info.farmers) {
        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
            assignOptimalTask(farmer);
        }
    }

    // 调试信息
    string stageInfo = (stage == 1) ? "Stage1" : "Stage2";
    DebugText(stageInfo + " - 砍树:" + to_string(resourceTargets.current_woodcutters) + "/" + to_string(resourceTargets.target_woodcutters) +
              " 打猎:" + to_string(resourceTargets.current_hunters) + "/" + to_string(resourceTargets.target_hunters) +
              " 采石:" + to_string(resourceTargets.current_miners) + "/" + to_string(resourceTargets.target_miners) +
              " 捕鱼:" + to_string(fishing_boat_count) + "/" + to_string(resourceTargets.target_fishers));
    if (stage == 1) {
        string popStatus = stage1PopControl.saving_for_upgrade ? "积累中" : "正常生产";
        DebugText("Stage1人口控制: " + to_string(currentPop) + "/" +
                  to_string(stage1PopControl.max_population_stage1) +
                  " 状态:" + popStatus + " 食物:" + to_string(info.Meat) + "/500");
    }
    if (stage == 2) {
        DebugText("战船数量: " + to_string(naval.current_warships) + "/" + to_string(naval.target_warships) +
                  " 敌方大陆: " + (exploration.enemy_mainland_found ? "已发现" : "未发现"));
    }
}

